package exampleQuestions;

import java.util.LinkedList;

public class CrackingTheCodeTenPointThree {

	/**
	 * Design an algorithm to find the kth number such that the only prime
	 * factors are 3, 5, and 7.
	 */
	public static void main(String[] args) {

		System.out.println(getKthNumber(12));
	}

	private static int getKthNumber(int n) {

		LinkedList<Integer> queue1 = new LinkedList<Integer>();
		LinkedList<Integer> queue2 = new LinkedList<Integer>();
		LinkedList<Integer> queue3 = new LinkedList<Integer>();

		final int three = 3;
		final int five = 5;
		final int seven = 7;

		int result = -1;

		if (n == 1) {
			return 1;
		} else {
			n--;

			queue1.addLast(three);
			queue2.addLast(five);
			queue3.addLast(seven);

			while (n > 0) {

				int n1 = queue1.getFirst();
				int n2 = queue2.getFirst();
				int n3 = queue3.getFirst();
				n--;

				if (n1 < n2 && n1 < n3) {
					result = queue1.removeFirst();

					queue1.addLast(n1 * three);
					queue2.addLast(n1 * five);
					queue3.addLast(n1 * seven);
					
				} else if (n2 < n1 && n2 < n3) {
					result = queue2.removeFirst();

					queue2.addLast(n2 * five);
					queue3.addLast(n2 * seven);
				} else {
					result = queue3.removeFirst();

					queue3.addLast(n3 * seven);
				}
			}

			return result;
		}

	}

}
